import React from "react";
import client from "webpack-theme-color-replacer/client";

const themeConfig = require("../themeConfig");

/** 主题相关工具 */
const ThemeTools = {
	/** 默认主题 */
	THEME_DEFAULT_TYPE: "default",
	/** 永辉生活主题 */
	THEME_LIFE_TYPE: "yhLife",
	/** 获取当前主题类型 */
	getTheme() {
		let key = "yhLife";
		if (
			typeof window !== "undefined" &&
			window.location.search &&
			window.location.search.indexOf("theme") > -1
		) {
			let theme = window.location.search
				.split("&")
				.filter(v => v.indexOf("theme") > -1)[0];
			if (theme) {
				key = theme.split("=")[1];
			}
		}
		return key;
	},
	/** 初始化方法 */
	init(cb) {
		const key = this.getTheme();
		if (themeConfig[key]) {
			client.changer.changeColor(themeConfig[key]["colors"], Promise).then(cb);
		} else {
			cb();
		}
	}
};
/** 只在默认主题下渲染children,该组件不接受除了children以外的任何参数 */
const ThemeDefault = ({ children }) => (
	<>{ThemeTools.getTheme() === ThemeTools.THEME_DEFAULT_TYPE && children}</>
);
/** 只在永辉生活下渲染children,该组件不接受除了children以外的任何参数 */
const ThemeLife = ({ children }) => (
	<>{ThemeTools.getTheme() === ThemeTools.THEME_LIFE_TYPE && children}</>
);

/** 如果是永辉生活的主题,返回t1,如果不是返回t2 */
ThemeLife.switch = (t1, t2) =>
	ThemeTools.getTheme() === ThemeTools.THEME_LIFE_TYPE ? t1 : t2;
/** 如果是默认主题 返回t1,如果不是返回t2*/
ThemeDefault.switch = (t1, t2) =>
	ThemeTools.getTheme() === ThemeTools.THEME_DEFAULT_TYPE ? t1 : t2;
export default ThemeTools;
export { ThemeDefault, ThemeLife };
